package zero.tech.games.log.hot;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import zero.tech.core.data.PageBean;
import zero.tech.games.common.RedisConsts;
import zero.tech.games.entity.log.LogPlayback;
import zero.tech.games.log.data.res.ResPlayback;
import zero.tech.games.log.mapper.LogPlaybackMapper;
import zero.tech.redis.cache.RedisUtil;

@Component
public class LogPlaybackUtil {
	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	private LogPlaybackMapper logPlaybackMapper;
	@SuppressWarnings("unchecked")
	public PageBean<ResPlayback> listPlaybackByPage(int uid, int club_id, int game_id, int page, int pageLength,Date begin,Date end) {
		PageBean<ResPlayback> pageBean=(PageBean<ResPlayback>) redisUtil.hget(RedisConsts.HOT_LOG_PLAYBACK_PAGE+"_"+uid+"_"+club_id+"_"+game_id,page+"_"+pageLength+"_"+begin.getTime()+"_"+end.getTime());
		if(pageBean==null) {
			int totalCount=logPlaybackMapper.totalCount(uid,club_id,game_id,begin,end);
			int start=page*pageLength;
			List<ResPlayback> list=logPlaybackMapper.findLogPlaybackListByPage(uid,club_id,game_id,start,pageLength,begin,end);
			pageBean = new PageBean<>(totalCount, pageLength, page, list);
			redisUtil.hset(RedisConsts.HOT_LOG_PLAYBACK_PAGE+"_"+uid+"_"+club_id+"_"+game_id,page+"_"+pageLength+"_"+begin.getTime()+"_"+end.getTime(), pageBean,5*60);
		}
		return pageBean;
	}
	public LogPlayback getPlaybackDetail(int uid, int club_id, int game_id, String room_id, String play_code, Date begin, Date end) {
		LogPlayback logPlayback= (LogPlayback) redisUtil.get(RedisConsts.HOT_LOG_PLAYBACK+"_"+uid+"_"+club_id+"_"+game_id+"_"+room_id+"_"+play_code+"_"+begin.getTime()+"_"+end.getTime());
		if(logPlayback==null) {
			logPlayback=logPlaybackMapper.getLogPlayback(uid,club_id,game_id,room_id,play_code,begin,end);
			if(logPlayback!=null) {
				redisUtil.set(RedisConsts.HOT_LOG_PLAYBACK+"_"+uid+"_"+club_id+"_"+game_id+"_"+room_id+"_"+play_code+"_"+begin.getTime()+"_"+end.getTime(), logPlayback, 1*60*60);
			}
		}
		return logPlayback;
	}
	public void insertBatch(List<LogPlayback> logPlaybacks) {
		logPlaybackMapper.insertBatch(logPlaybacks);
		for(LogPlayback logPlayback :logPlaybacks) {
			String key=logPlayback.getUid()+"_"+logPlayback.getClub_id()+"_"+logPlayback.getGame_id();
			redisUtil.del(RedisConsts.HOT_LOG_PLAYBACK_PAGE+"_"+key);
		}
	}
}
